package com.zlm.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 郑
 */
public class JWTUtil {

    private static String sign_key="#%!WS&^*@";

    /**
     * 生成token
     * @param paramMap
     * @return
     */
    public static String getToken(Map<String, String> paramMap){
        HashMap<String, Object> map = new HashMap<>();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);
        JWTCreator.Builder builder = JWT.create().withHeader(map);
        //payload
        paramMap.forEach((k,v) -> {
            builder.withClaim(k,v);
        });
        return builder
                    .withExpiresAt(instance.getTime()) //过期时间
                    .sign(Algorithm.HMAC256(sign_key));//签名

    }

    /**
     * 验证token
     * @param token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(sign_key)).build().verify(token);
    }

    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(sign_key)).build().verify(token);
        return decodedJWT;
    }
}
